<template>
  <div class="app-container">
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
      :row-class-name="tableRowClassName">
      <el-table-column label="期数" prop="pay_id" align="center">
        <template slot-scope="{row}">
          <span v-if="row.is_first">首付款</span>
          <span v-else>第{{ key }}期</span>
        </template>
      </el-table-column>
      <el-table-column label="总额" prop="total_money" align="center">
        <template slot-scope="{row}">
          <span>{{ row.total_money }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商家分成" prop="money_rate" align="center">
        <template slot-scope="{row}">
          <span>{{ row.merchant_money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司本金" prop="time_date" align="center">
        <template slot-scope="{row}">
          <span>{{ row.myself_money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际还款日期" prop="time_date" align="center">
        <template slot-scope="{row}">
          <span>{{ row.paid_time|formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否还款" prop="is_paid" align="center">
        <template slot-scope="{row}">
          <span v-if="row.is_paid==3">待审核</span>
          <span v-if="row.is_paid==2">部分还款</span>
          <span v-if="row.is_paid==1">已还款</span>
          <span v-if="row.is_paid==0">未还款</span>
        </template>
      </el-table-column>

            <el-table-column label="交易凭证" align="center">
              <template slot-scope="{row}">
                <span v-for="(item,index) in row.image"><el-image
            style="width: 20px; height: 20px"
            :src="item.path"
             @click="openImages(item.path)"></el-image></span>
              </template>
            </el-table-column>
      <el-table-column label="已还金额" prop="time_date" align="center">
        <template slot-scope="{row}">
          <span>{{ row.paid_money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button size="mini" type="danger"  @click="handleCreate(row)" v-if="row.is_paid==1" >
            记账
          </el-button>
          <el-button size="mini" type="warning" @click="handleCollection(row)" v-if="row.is_paid!==1">
            设置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormCollectionVisible" width="960px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 70%; margin-left:70px;">
        <el-form-item label="是否付款">
          <el-radio v-model="temp.is_paid" label="0">未付款</el-radio>
          <el-radio v-model="temp.is_paid" label="1">已付款</el-radio>

        </el-form-item>
        <el-form-item label="已还金额">
            <el-input v-model="temp.paid_money" type="number" placeholder="请输入已还金额" />
        </el-form-item>
     <el-form-item label="上传付款凭证">
          <el-image style="width: 148px; height: 148px" :src="item.path"  v-for="(item,index) in image_list"></el-image>
          <el-upload class="avatar-uploader" :action="UploadUrl()" list-type="picture-card" :on-success="handUploadSuccess"
            :before-upload="beforeAvatarUpload" :headers="myHeaders">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormCollectionVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createCollection():updateCollection()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogImageVisible">
      <el-image :src="path"></el-image>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogImageVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataRecordForm" :rules="rule_record" :model="record" label-position="left" label-width="100px">

        <el-form-item label="明细" prop="sort">
          <el-select v-model="record.sort" placeholder="请选择市" class="filter-item">
            <el-option :label="item.name" :value="item.id" v-for="(item,index) in this.sort_list" />

          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="total_money">
          <el-input v-model="record.total_money" type="number" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="我方账户" prop="my_account">
          <el-input v-model="record.my_account" type="text" placeholder="请输入坏账" />
        </el-form-item>
        <el-form-item label="他方账户" prop="ta_account">
          <el-input v-model="record.ta_account" type="text" placeholder="请输入他方账户" />
        </el-form-item>
        <el-form-item label="交易流水" prop="out_trade_no">
          <el-input v-model="record.out_trade_no" type="text" placeholder="请输入交易流水" />
        </el-form-item>
        <el-form-item label="支付方式" prop="pay_method">
          <el-select v-model="record.pay_method" placeholder="请选择支付方式" class="filter-item">
            <el-option label="公对公" value="1" />
            <el-option label="公对私" value="2" />
            <el-option label="私对私" value="3" />
            <el-option label="私对公" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付渠道" prop="pay_channel">
          <el-select v-model="record.pay_channel" placeholder="请选择支付渠道" class="filter-item">
            <el-option label="支付宝" value="1" />
            <el-option label="微信" value="2" />
            <el-option label="银行转账" value="3" />
          </el-select>
        </el-form-item>
       <el-form-item label="上传凭证">
                  <el-upload
                    class="avatar-uploader"
                    :action="UploadUrl()"
                    list-type="picture-card"

                    :on-success="handUploadRecordSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="myHeaders"
                     >

        <i  class="el-icon-plus"></i>

        </el-upload>
              </el-form-item>
      </el-form>
      <div class="dialog-footer" style="padding-right: 0px;">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='record'?createData():updateData()">
          确认
        </el-button>
      </div>

      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
  import {
    createPaymentRecord,
    getOrderPaymentType
  } from '@/api/finance'
  import {
    getOrderPaymentMerchantList,
    setCollectionMerchant
  } from '@/api/collection'
  import {
    formatDate
  } from '@/utils/formatDate.js'
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils'
  export default {
    name: 'orderPaymentTable',

    directives: {
      waves
    },
    filters: {
      formatDate(time) {
        time = time * 1000
        let date = new Date(time)
        if (time == 0) {
          return "暂无"
        }
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    data() {
      return {
        action: process.env.VUE_APP_BASE_API + 'upload/file',
        myHeaders: {
          token: this.$store.getters.token
        },
        textMap: {
          record :'日记账',
          create: '设置'
        },
        tableKey: 0,
        list: [],
        image_list: [],
        path: '',

        sale_list: [],
        sort_list: [],
        listLoading: true,
        dialogFormCollectionVisible: false,
        dialogRecordVisible: false,
        dialogImageVisible: false,
        dialogFormVisible:false,
        dialogStatus: '',
        temp: {
          attach_id: [],
          paid_money:0,
          is_paid: "0"
        },
        record: {
          type: 2,
          pay_id: [],
          order_id:0,
          total_money: 0,
          benjin: 0,
          service: 0,
          buy: 0,
          rate: 0,
          fine: 0,
          bad: 0,
          my_account: null,
          ta_account: null,
          out_trade_no: null,
          pay_method: null,
          pay_channel: null,

          images:[],
          status: '1'
        },
        rules: {
           paid_money: [{
            required: true,
            message: '实付金额',
            trigger: 'blur'
          }],
          is_paid: [{
            required: true,
            message: '付款状态必须选择',
            trigger: 'blur'
          }],
        },
        rule_record: {
          sort: [{
            required: true,
            message: '明细必须选择',
            trigger: 'change'
          }],
          pay_id: [{
            required: true,
            message: '分期期数必须选择',
            trigger: 'blur'
          }],
          my_account: [{
            required: true,
            message: '我方账户必须输入',
            trigger: 'change'
          }],
          ta_account: [{
            required: true,
            message: '他方账号必须输入',
            trigger: 'change'
          }],
          out_trade_no: [{
            required: true,
            message: '交易流水必须输入',
            trigger: 'change'
          }],
          pay_method: [{
            required: true,
            message: '交易方式必须选择',
            trigger: 'change'
          }],
          pay_channel: [{
            required: true,
            message: '交易渠道必须选择',
            trigger: 'change'
          }]

        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        let order_id = this.$route.params.order_id
        getOrderPaymentMerchantList(order_id).then(resp => {
          this.list = resp.data

          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      },
      detail(order_id, pay_id) {
        this.$router.push('/collect/detail/' + order_id + "/" + pay_id)
      },
      handleCreate(row) {

        getOrderPaymentType(2).then(res => {
          this.sort_list = res.data;
        })
        this.dialogStatus = 'record'
        this.record.pay_id=[],
        this.record.pay_id.push(row.pay_id)
        console.log(this.record.pay_id);
        this.record.order_id=row.order_id
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataRecordForm'].clearValidate()
        })
      },
      createData() {
        if(this.record.images.length==0){
               this.$message.error('凭证必须上传')
        }else{
        this.$refs['dataRecordForm'].validate((valid) => {
          if (valid) {
            console.log(this.record)
            createPaymentRecord(this.record).then(() => {
             // this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000,
                onClose: this.getList()
              })
            })
          }
        })
        }
      },
      handleCollection(row) {
        this.dialogStatus = 'create'
        this.dialogFormCollectionVisible = true

        this.temp.is_paid=row.is_paid.toString()
        this.temp.paid_money=row.paid_money
        this.pay_id = row.pay_id
        console.log(row.image)
        this.image_list = row.image

let that=this
row.image.forEach(function (item, index) {
    console.log(item.attach_id);
that.temp.attach_id.push(item.attach_id)
});
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
          openImages(path){
            this.dialogImageVisible=true;
            this.path=path
          },
      createCollection() {
        console.log(this.temp)
        if ((this.temp.is_paid == '1') && (this.temp.attach_id.length== '0'))  {
          this.$notify.error({
            title: '错误',
            message: '已付款必须上传付款凭证',
            type: 'danger',
            duration: 2000,
            onClose: this.getList()
          })
        } else {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
               setCollectionMerchant(this.pay_id, this.temp).then(() => {
                 this.list.unshift(this.temp)
                 this.dialogFormCollectionVisible = false
                 this.$notify({
                   title: 'Success',
                   message: 'Created Successfully',
                   type: 'success',
                   duration: 2000,
                   onClose: this.getList()
                 })
               })
            }
          })
        }
      },
      handUploadSuccess(res, file) {
        this.temp.attach_id.push(res.data.attach_id)
        this.imageUrl = URL.createObjectURL(file.raw);
        console.log(this.temp)
      },
      handUploadRecordSuccess(res, file) {
        this.record.images.push(res.data.attach_id)
        this.imageUrl = URL.createObjectURL(file.raw);

      },
      beforeAvatarUpload(file) {
        console.log(file)
        let isJPG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if ((file.type === 'image/png') || (file.type === 'image/jpeg') || (file.type === 'image/gif')) {
          isJPG = true
        } else {
          isJPG = false
          this.$message.error('上传头像图片只能是 png,jpg,或者jif格式')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        console.log(isJPG && isLt2M)
        return isJPG && isLt2M
      },
      UploadUrl: function() {
        return this.action
      },
      tableRowClassName({
        row,
        rowIndex
      }) {

        if (row.is_overdue === 1) {
          return 'overdue-row';

        }
        return '';
      }

    }
  }
</script>

<style>
  .el-table .overdue-row {
    background: #F44336;
  }
</style>
